<?php

/**
 * @user magein
 * @date 2023/12/1 13:33
 */

namespace magein\sms\platform;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use magein\utils\Result;
use magein\sms\Target;
use Psr\Http\Message\ResponseInterface;

abstract class Platform
{
    /**
     * 发送目标信息
     * @var Target|null
     */
    protected $target = null;

    /**
     * 使用账号配置
     * @var array
     */
    protected $config = [];

    /**
     * @return string
     */
    public abstract function version(): string;

    /**
     * 发送验证码
     * @return Result
     */
    public abstract function code(): Result;

    /**
     * 发送类
     * @return Result
     */
    public abstract function send(): Result;

    /**
     * 初始化
     * @param $params
     * @return mixed
     */
    public abstract function init($params);

    /**
     * 响应结果
     * @var Response|null
     */
    protected $response = null;

    /**
     * 请求错误信息(curl请求的错误信息)
     * @var string
     */
    protected $error = '';

    /**
     * 请求的结果
     * @var string
     */
    protected $content = '';

    public function __construct($params)
    {
        $this->init($params);
    }

    public function setTarget(Target $target): void
    {
        $this->target = $target;
    }

    /**
     * 使用账号配置
     * @param array $config
     * @return void
     */
    public function setConfig(array $config): void
    {
        $this->config = $config;
    }

    /**
     * @param $uri
     * @param $options
     * @return ResponseInterface|null
     */
    public function post($uri, $options): ?ResponseInterface
    {
        try {

            if (empty($options)) {
                $options = [];
            }

            $options['verify'] = false;

            $client = new Client();
            $response = $client->post($uri, $options);

            if ($response->getStatusCode() === 200) {
                $this->response = $response;
                $this->content = $response->getBody()->getContents();
            }

        } catch (GuzzleException $exception) {
            $response = null;
            $this->error = $exception->getMessage();
        }

        return $response;
    }

    public function toArray()
    {
        return $this->content ? json_decode($this->content, true) : [];
    }
}